package com.hetao.assist;

import com.alibaba.fastjson.JSON;
import com.hetao.assist.model.ResponseObject;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hetao
 * @date 2019/1/10
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();


//        modelAndView.addObject(object);

        try {
            response.setStatus(HttpStatus.OK.value()); //设置状态码
            response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
            response.setCharacterEncoding("UTF-8"); //避免乱码
            response.setHeader("Cache-Control", "no-cache, must-revalidate");

            ResponseObject<Object> object = new ResponseObject<>();
            object.setStatus(2);
            logger.error(ExceptionUtils.getStackTrace(ex));
            object.setMsg("接口调用发生了错误，请重试!");

            response.getWriter().write(JSON.toJSONString(object));
        } catch (IOException e) {
            logger.error("URI:{}  {} ", httpServletRequest.getRequestURI(), e);
        }

        return modelAndView;
    }
}
